'use strict';
var Hero = function(data){
		this.name = data.name;
		this.hp = data.hp;
		this.mp = data.mp;
		this.speed = data.speed;
		this.strength = data.strength;
		this.intelligence = data.intelligence;
		this.agility = data.agility;
		this.artifice = data.artifice;
		this.tenacity = data.tenacity;
		this.will = data.will;
		this.iconName = data.iconName;
		this.artName = data.artName;
}
var TheTable = function(className){
	this.className = className;
	this.rows = [];
	this.setCaption = function(caption){
		this.caption = caption;
	}
	this.addRow = function(tdContents, className){
		if (!className) {
			className = '';
		}
		var tds = [];
		for (var td in tdContents) {
			if (!tdContents[td].className) {
				tdContents[td].className = '';
			}
			if (!tdContents[td].content) {
				tdContents[td].content = '';
			}
			tds.push({'className' : tdContents[td].className, 'content' : tdContents[td].content, 'colSpan' : tdContents[td].colSpan});
		}
		this.rows.push({'className' : className, 'tds' : tds});
	}
	this.getString = function(){
		var result = '<table';
		if (this.className) {
			result += ' class="' + this.className + '"';
		}
		result += '>';
		if (this.caption) {
			result += '<caption class="' + this.caption.className + '">' + this.caption.content + '</caption>';
		}
		for (var row in this.rows) {
			result += '<tr';
			if (row.className) {
				result += ' class="' + row.className + '"';
			}
			result += '>';
			for (var col in this.rows[row].tds) {
				result += '<td';
				if (this.rows[row].tds[col].className) {
					result += ' class="' + this.rows[row].tds[col].className + '"';
				}
				if (this.rows[row].tds[col].colSpan) {					
					result += ' colspan="' + this.rows[row].tds[col].colSpan + '"';
				}
				result += '>';
				if (this.rows[row].tds[col].content) {
					result += this.rows[row].tds[col].content;
				}				
				result += '</td>';
			}
			result += '</tr>';
		}
		result += '</table>';
		return result;
	}
}
//dev route
var baseUrl = 'http://symfony.local/';
//prod route
//var baseUrl = Routing.generate('home', {}, true);
var cdImage = 'images/cd.png';
var primeImage = 'images/prime.png';
var costImage = 'images/cost.png';
var getTooltipContainer = function(){
	var mess = $('#mess');
	if (mess.length == 0) {
		mess = $('<div id="mess"></div>');
		$('body').append(mess);
	}
	return mess;
}
var container = getTooltipContainer();
var hideToolTip = function() {
	container.css('visibility', 'hidden');
}
var positionTip = function(e) {
	var newX = e.pageX + 15;
	var newY = e.pageY + 15;
	var theWidth = $(document).scrollLeft() + $(window).width();
	var theHeight = $(document).scrollTop() + $(window).height();
	if (theWidth < e.pageX + 15 + container.outerWidth()) {
		newX = e.pageX - 15 - container.outerWidth();
	}
	if (theHeight < e.pageY + 15 + container.outerHeight()) {
		newY = e.pageY - 15 - container.outerHeight();
	}
	container.css('left', newX + 'px');
	container.css('top', newY + 'px');
}
var heroes = [];
var getHeroesData = function() {
	if (heroes.length == 0) {
		$.ajax({
			async: false,
			type: 'get',
			url: Routing.generate('heroes_getjson', { heroId: 0 }),
			dataType : "json",
			success: function (data) {
				heroes = data;
			} 
		});
	}
	return heroes;
}
var talents = [];
var getTalentsData = function() {
	if (talents.length == 0) {
		$.ajax({
			async: false,
			type: 'get',
			url: Routing.generate('talents_getjson', { talentId: 0 }),
			dataType : "json",
			success: function (data) {
				talents = data;
			} 
		});
	}
	return talents;
}
var mySettings = {};

var app = angular.module('theApp', []);

/* Directives */
app.directive("tooltip", function () {
	return {
		restrict: 'A',
		//transclude: true,
		//template: '<div class="" ng-transclude></div>',
		//scope: {},
		link: function(scope, element, attrs) {
			var mess = $('#mess');
			if (mess.length == 0) {
				mess = $('<div id="mess"></div>');
				$('body').append(mess);
			}
			var showToolTip = function() {
				if (attrs.tooltip) {
					mess.empty();
					mess.text(attrs.tooltip);
				}
				mess.css('visibility', 'visible');
			}
			var hideToolTip = function() {
				mess.css('visibility', 'hidden');
			}
			var positionTip = function(e) {
				var newX = e.pageX + 15;
				var newY = e.pageY + 15;
				mess.css('left', newX + 'px');
				mess.css('top', newY + 'px');
			}
			element.bind('mouseenter', showToolTip);
			element.bind('mouseleave', hideToolTip);
			element.bind('mousemove', positionTip);
		}
	}
});
app.directive("herotooltip", function ($http) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			var contentLoaded = false;			
			var heroTip = $("<div class='heroTip'><div class='imageContainer'></div><div class='statsContainer'></div></div>");
			var getContent = function() {
				if (!contentLoaded) {
					container.empty();
					$http.get(Routing.generate('heroes_getjson', { heroId: attrs.herotooltip })).success(function(data) {			
						var statTable = new TheTable('tableClass');
						statTable.setCaption({'content':data.name, 'className':''});
						statTable.addRow([{'content' : 'Здоровье:'},{'className' : 'toRight', 'content' : data.hp}]);
						statTable.addRow([{'content' : 'Энергия:'},{'className' : 'toRight', 'content' : data.mp}]);
						statTable.addRow([{'content' : 'Скорость:'},{'className' : 'toRight', 'content' : data.speed}]);
						statTable.addRow([{'content' : 'Сила:'},{'className' : 'toRight', 'content' : data.strength}]);
						statTable.addRow([{'content' : 'Разум:'},{'className' : 'toRight', 'content' : data.intelligence}]);
						statTable.addRow([{'content' : 'Проворство:'},{'className' : 'toRight', 'content' : data.agility}]);
						statTable.addRow([{'content' : 'Хитрость:'},{'className' : 'toRight', 'content' : data.artifice}]);
						statTable.addRow([{'content' : 'Стойкость:'},{'className' : 'toRight', 'content' : data.tenacity}]);
						statTable.addRow([{'content' : 'Воля:'},{'className' : 'toRight', 'content' : data.will}]);
						var content = statTable.getString();
						heroTip.find('div.statsContainer').empty().append(content);
						heroTip.find('div.imageContainer').empty().append('<img src="' + baseUrl + 'images/heroes/' + data.artName + '"/>');
						container.append(heroTip);
						contentLoaded = true;
					}).error(function(data) {
						contentLoaded = false;
						container.text('Error loading');
					});					
				}				
			}
			var showToolTip = function() {
				getContent();
				container.empty().append(heroTip);
				container.css('visibility', 'visible');
			}
			element.bind('mouseenter', showToolTip);
			element.bind('mouseleave', hideToolTip);
			element.bind('mousemove', positionTip);
		}
	}
});
app.directive("talenttooltip", function ($http) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
//			var contentLoaded = false;
//			var talentTip = $("<div class='span4'></div>");
//			var getContent = function() {
//				if (!contentLoaded) {
//					container.empty();
//					$http.get(Routing.generate('talents_getjson', { talentId: attrs.talenttooltip })).success(function(data) {			
//
//						var talentTable = new TheTable('tableClass');
//						var caption = {'content':data.name, 'className':''};
//						if (data.rarity) {
//							caption.className = 'rarity' + data.rarity.id;
//						}
//						talentTable.setCaption(caption);
//						var useCost = '';
//						if (data.useCost) {
//							useCost = '<img src="' + baseUrl + costImage + '" />' + data.useCost;
//						}
//						var coolDown = '';
//						if (data.coolDown) {
//							coolDown = '<img src="' + baseUrl + cdImage + '" />' + data.coolDown;
//						}
//						var learnCost = '';
//						if (data.learnCost) {
//							learnCost = '<img src="' + baseUrl + primeImage + '" />' + data.learnCost;
//						}
//						talentTable.addRow([{'content' : data.type}, {'content' : useCost}, {'content' : coolDown}]);
//						talentTable.addRow([{'content' : data.description, 'colSpan' : 3}]);
//						talentTable.addRow([{'content' : data.landEffect, 'colSpan' : 3}]);
//						talentTable.addRow([{'content' : learnCost, 'colSpan' : 3}]);
//						var content = talentTable.getString();
//						talentTip.empty().append(content);
//						container.append(talentTip);
//						contentLoaded = true;
//					}).error(function(data) {
//						contentLoaded = false;
//						container.text('Error loading');
//					});					
//				}				
//			}
//			var showToolTip = function() {				
//				getContent();
//				container.empty().append(talentTip);
//				container.css('visibility', 'visible');
//			}
//			element.bind('mouseenter', showToolTip);
//			element.bind('mouseleave', hideToolTip);
//			element.bind('mousemove', positionTip);
                    var contentLoaded = false;
                    var content = '';
                    $(element).tooltip({ /*position: { my: "left bottom-150", at: "left bottom", collision: "flipfit" },*/ hide: false, show: false, tooltipClass: "my-custom-tooltip", content: '... Загрузка ...', open: function(){
						var elem = $(this);
                        if (!contentLoaded) {                            
                            $http.get(Routing.generate('talents_getjson', { talentId: attrs.talenttooltip })).success(function(data) {
                                    var talentTable = new TheTable('tableClass');
                                    var caption = {'content':data.name, 'className':''};
                                    if (data.rarity) {
                                            caption.className = 'rarity' + data.rarity.id;
                                    }
                                    talentTable.setCaption(caption);
                                    var useCost = '';
                                    if (data.useCost) {
                                            useCost = '<img src="' + baseUrl + costImage + '" />' + data.useCost;
                                    }
                                    var coolDown = '';
                                    if (data.coolDown) {
                                            coolDown = '<img src="' + baseUrl + cdImage + '" />' + data.coolDown;
                                    }
                                    var learnCost = '';
                                    if (data.learnCost) {
                                            learnCost = '<img src="' + baseUrl + primeImage + '" />' + data.learnCost;
                                    }
                                    talentTable.addRow([{'content' : data.type}, {'content' : useCost}, {'content' : coolDown}]);
                                    talentTable.addRow([{'content' : data.description, 'colSpan' : 3}]);
                                    talentTable.addRow([{'content' : data.landEffect, 'colSpan' : 3}]);
                                    talentTable.addRow([{'content' : learnCost, 'colSpan' : 3}]);
                                    var content = talentTable.getString();
                                    elem.tooltip('option', 'content', content);
									contentLoaded = true;
                            }).error(function(data) {
                                    elem.tooltip('option', 'content', 'Ошибка загрузки');
                            });
                        }
                    } 
                });
            }
	}
});
app.directive("colorpick", function () {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			//$('#cp3').colorpicker();
			element.colorpicker().on('hide', function(ev){
				element.text(ev.color.toHex());
			});
		}
	}
});
app.directive("toolbar", function ($http, $compile) {
	var getMarkitupSettings = function(scope) {
		if ($.isEmptyObject(mySettings)) {
			var aHeroDropDown = [];
			var dHeroDropDown = [];
			var heroesData = getHeroesData();
			for (var hero in heroesData) {
				var obj = {};
				obj.name = heroesData[hero].name;
				obj.replaceWith = '[hero=' + heroesData[hero].name + ', type=icon]';
				if (heroesData[hero].side == 'a') {
					aHeroDropDown.push(obj);
				} else if(heroesData[hero].side == 'd') {
					dHeroDropDown.push(obj);
				}		
			}
			var talentsData = getTalentsData();
			var buildDialog = $compile($('<div talentbuild ></div>'))(scope);
			$('body').append(buildDialog);
			buildDialog.dialog({ autoOpen: false, modal: true, width: 440});
			mySettings = {
				onShiftEnter:  	{keepDefault:false, replaceWith:'<br />\n'},
				onCtrlEnter:  	{keepDefault:false, openWith:'\n<p>', closeWith:'</p>'},
				onTab:    		{keepDefault:false, replaceWith:'    '},
				markupSet:  [ 	
						{name:'Bold', openWith:'[b]', closeWith:'[/b]' },
						{name:'Italic', openWith:'[i]', closeWith:'[/i]'  },
						{name:'Stroke through', openWith:'[del]', closeWith:'[/del]' },
						{name:'Color', className:'color', dropMenu: [
								{ name:'Red', openWith:'[color=f00]', closeWith:'[/color]'},
								{ name:'Green', openWith:'[color=0f0]', closeWith:'[/color]'},
								{ name:'Blue', openWith:'[color=00f]', closeWith:'[/color]'},
								{ name:'Gold', openWith:'[color=ffd700]', closeWith:'[/color]'}
						  ]
						},
						{name:'Заголовки', className:'size', dropMenu: [
								{ name:'H1', openWith:'[h1]', closeWith:'[/h1]'},
								{ name:'H2', openWith:'[h2]', closeWith:'[/h2]'},
								{ name:'H3', openWith:'[h3]', closeWith:'[/h3]'},
								{ name:'H4', openWith:'[h4]', closeWith:'[/h4]'},
								{ name:'H5', openWith:'[h5]', closeWith:'[/h5]'},
								{ name:'H6', openWith:'[h6]', closeWith:'[/h6]'}
						  ]
						},
						{separator:'---------------' },
						{name:'Bulleted List', className:'bList', openWith:'    [li]', closeWith:'[/li]', multiline:true, openBlockWith:'[ul]\n', closeBlockWith:'\n[/ul]'},
						{name:'Numeric List', className:'nList', openWith:'    [li]', closeWith:'[/li]', multiline:true, openBlockWith:'[ol]\n', closeBlockWith:'\n[/ol]'},
						{separator:'---------------' },
						{name:'Picture', className:'picture', replaceWith:'[image source=[![Source:!:http://]!]]' },
						{name:'Link', className:'link', openWith:'[link source=[![Link:!:http://]!]]', closeWith:'[/link]', placeHolder:'Your text to link...' },
						{name:'Video', className:'video', replaceWith:'[video source=[![YouTube embed video link:!:http://]!]]'},
						{separator:'---------------' },
		//                {name:'Hero', className:'hero', replaceWith:'[hero=[![Имя:!:]!], type=icon]' },
						{name:'Докты', className:'doctr', dropMenu: dHeroDropDown},
						{name:'Адорнийцы', className:'adorn', dropMenu: aHeroDropDown},
						{name:'Talent', className:'talent', replaceWith:'[talent=[![Талант:!:]!], type=icon]' },
						{separator:'---------------' },
						{name:'Physical damage', className:'ad', replaceWith:'[icon=ad]' },
						{name:'Magical damage', className:'ap', replaceWith:'[icon=ap]' },
						{name:'Magical damage', className:'ap', replaceWith: function (markItUp) {
								buildDialog.dialog('open');
								return 'This is a button that injects text!';
							} 
						},

		//				{name:'Preview', className:'preview',  call:'preview'}
				]
			}
		}
		return mySettings;
	}
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			element.markItUp(getMarkitupSettings(scope));
		}
	}
});
app.directive("chapterscontainer", function ($compile) {
	var addButton = $('<a href="#">Добавить раздел</a>');
//	var appendDelButton = function (itemToDel) {
//		var delButton = $('<a href="#">Удалить раздел</a>');		
//		delButton.on('click', function(e) {
//			e.preventDefault();
//			if (confirm("Вы уверены?")) {
//				itemToDel.remove();
//			}			
//		});
//		itemToDel.append(delButton);
//	}	
	var insertForm = function(container, prototype, scope){
		var ids = [];
		var newId = 0;
		container.find('input').filter(function() {
			var matches = this.id.match(/guide_chapters_(\d)+_title/);
			if (matches != null) {
				ids.push(matches[1]);
			}
		});
		if (ids.length > 0) {
			newId = +ids[ids.length - 1] + 1;			
		}
		var newForm = prototype.replace(/__name__/g, newId);
		var chapterMenu = $('<div chaptermenu class="toRight"></div>');
		var newFormContainer = $('<div class="chapter"></div>').append(chapterMenu).append(newForm);
		newFormContainer = $compile(newFormContainer)(scope);
		//appendDelButton(newFormContainer);
		container.append(newFormContainer);
	}
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			addButton.on('click', function(e){
				e.preventDefault();
				insertForm(element, attrs.dataprototype, scope);
			});
			element.append(addButton);
		}
	}
});
app.directive("chaptermenu", function () {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			var collapseButton = $('<a href="#">-</a>');
			var closeButton = $('<a href="#">&times;</a>');
			var isCollapsed = false;
			closeButton.on('click', function(e){
				e.preventDefault();
				if (confirm("Вы уверены?")) {
					element.parent().remove();
				}				
			});
			collapseButton.on('click', function(e){
				e.preventDefault();
				if (isCollapsed) {
					element.parent().find('div.markItUp').show('slow');
					collapseButton.empty().text('-');
					isCollapsed = false;
				} else {
					element.parent().find('div.markItUp').hide('slow');
					collapseButton.empty().text('+');
					isCollapsed = true;
				}
			});
			element.append(collapseButton);
			element.append(closeButton);		
		}
	}
});
var TalentTable = function(rows, cols) {
	this.rowsCount = rows;
	this.colsCount = cols;
	this.rows = [];
	this.table = $('<table></table>');
	var revertNumber = function (number, revertBy){
		return Math.abs(number - revertBy + 1);
	}
	for (var i = 0; i < rows; i++) {
		this.rows.push({'row':$('<tr></tr>'), 'cols':[]});
		for(var j = 0; j < cols; j++) {
			this.rows[i].cols.push($('<td row="' + revertNumber(i - 1, this.rowsCount) + '" col="' + (j + 1) + '"></td>'));
			this.rows[i].row.append(this.rows[i].cols[j]);
		}
		this.table.append(this.rows[i].row);
	}
	this.getTable = function () {
		return this.table;
	}
	this.getCell = function (row, column) {
		return this.rows[revertNumber(row - 1, this.rowsCount)].cols[column - 1];
	}
        this.clear = function () {
            for (var i in this.rows) {
                for (var j in this.rows[i].cols) {
                    this.rows[i].cols[j].empty();
                }
            }
        }
}
app.directive("talentbuild", function ($compile) {
	return {
		restrict: 'A',
		link: function(scope, element, attrs) {
			var talentsDialog = $('<div>Talents list</div>');
			talentsDialog.dialog({ autoOpen: false, modal: true, width: 500});
			$('body').append(talentsDialog);
			var theTable = new TalentTable(6, 6);
			element.append(theTable.getTable().addClass('talentTable'));
//                        theTable.getCell(1, 1).text('I');
//                        theTable.getCell(2, 1).text('II');
//                        theTable.getCell(3, 1).text('III');
//                        theTable.getCell(4, 1).text('IV');
//                        theTable.getCell(5, 1).text('V');
//                        theTable.getCell(6, 1).text('VI');
			var heroesData = getHeroesData();
			var talentsData = getTalentsData();
			var showTalentsModal = function() {
				var elem = $(this);				
				var lvl = elem.attr('row');
				var thisTalents = {};
				for (var i in talentsData) {
					if (talentsData[i].lvl == lvl && talentsData[i].heroId == 1) {
						if (!thisTalents[talentsData[i].rarity.id]){
							thisTalents[talentsData[i].rarity.id] = [];
						}
						thisTalents[talentsData[i].rarity.id].push(talentsData[i]);
					}
				}
				var rowz = 0;
				for (var i in thisTalents) {
					console.log(Math.ceil(thisTalents[i].length / 6));
				}
//				console.log(rowz);
				talentsDialog.dialog('open');				
			}
			var loadTalents = function (event) {
				var thisTalents = { "1" : [], "2" : [], "3" : [], "4" : [], "5" : [], "6" : []};
				var id = $(this).val();
				for (var index in talentsData) {
					if (talentsData[index].heroId === id) {
						thisTalents[talentsData[index].lvl].push(talentsData[index]);
					}
				}
				theTable.clear();
				for (var i in thisTalents) {
					for (var j in thisTalents[i]) {
						var talentImage = $compile($('<img talenttooltip="' + thisTalents[i][j].id + '"title="' + thisTalents[i][j].name + '" src="' + baseUrl + 'images/talents/' + thisTalents[i][j].iconName + '" />'))(scope);
//                      theTable.getCell(i, j + 1).append($('<img title="' + thisTalents[i][j].name + '" src="' + baseUrl + 'images/talents/' + thisTalents[i][j].iconName + '" />').tooltip({ content: "Awesome title!" }));
						theTable.getCell(i, j + 1).append(talentImage);
					}
				}
				for (var i = 1; i <= theTable.rowsCount; i++) {
					for (var j = 1; j <= theTable.colsCount; j++) {
						if (theTable.getCell(i, j).children().length === 0) {
							theTable.getCell(i, j).bind('click', showTalentsModal);
						}						
					}
				}
//                            console.log($(this).val());
//                            console.log(thisTalents);
//                            $('body').append(theTable.getTable().addClass('talentTable'));
			}

			var heroSelect = $('<select></select>');
			for (var heroid in heroesData) {
				if (heroesData[heroid].side === 'd') {
					heroSelect.append($('<option value="' + heroid + '">' + heroesData[heroid].name + '</option>'));
				}
			}
			element.append(heroSelect);
			heroSelect.bind('change', loadTalents);			
			heroSelect.trigger('change');
		}
	}
});
/* Controllers */

function ListSegmentCtrl($scope, $http, $compile) {
	var segmentLinkActive = 'Cancel segment';
	var segmentLinkInactive = 'Segment';
	var formContainerId = 'formContainer';
	var operationContainerId = 'operationContainer';
	var segmentStatus = false;
	var getContainer = function(id) {
		return '<div id="' + id + '"></div>';
	}
	//$scope.field = 'email';
	/*$scope.$watch('field', function(newValue) {
		alert(newValue);
	});*/
	$scope.listDivCheck = function(e) {
		e.stopPropagation();
		//$(e.currentTarget).children('input').first().prop("checked", true);
		$scope.listid = $(e.currentTarget).children('input').first().val();
		//$(e.currentTarget).children('input').first().trigger('click');
		if (segmentStatus) {
			var $container = $(e.currentTarget).children('#' + formContainerId);
			if (!$container.length) {
				$('#' + formContainerId).remove();
				segmentStatus = false;
			}
		}		
	}
	$scope.getSegmentForm = function(e) {
		e.preventDefault();
		e.stopPropagation();
		$scope.listid = $(e.currentTarget).siblings('input').first().val();
		if (segmentStatus) {
			$('#' + formContainerId).remove();
			$(e.target).text(segmentLinkInactive);
			segmentStatus = false;
		} else {	
			$(e.target).after(getContainer(formContainerId));
			$http.post(Routing.generate('account_campaign_segment'), {'listid': $scope.listid}).success
			(function(data) {			
				$compile(data)($scope).appendTo($('#' + formContainerId));
			}).error
			(function(data) {
				$compile(data)($scope).appendTo($('#' + formContainerId));
			});
			$(e.target).text(segmentLinkActive);
			segmentStatus = true;
		}

	}
  $scope.getOperationsForm = function() {
	  //$event.preventDefault();
	  //alert();
	  alert($scope.field);
	  /*$($scope.getContainer(operationContainerId));
	$http.post(Routing.generate('account_campaign_operation'), {'listid': $scope.listid, 'field': $scope.field}).success(function(data) {
		$compile(data)($scope).appendTo($('#' + formContainerId));		
	});	*/
  }
}

//PhoneListCtrl.$inject = ['$scope', '$http'];
/*
	  var foo;
	  var res = new Array();
	  for (foo in $event.target.nextElementSibling) {
		  res.push(foo);
	  }
	  alert(res.sort()); 
 */
